<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\GrantLog;
use think\Log;
use WeChatPay\Formatter;
use WeChatPay\Crypto\Rsa;
use WechatPay\GuzzleMiddleware\Util\AesUtil;

class Notify extends Api
{
    protected $noNeedLogin = ['*'];

    /**
     * 商户转账通知
     * @return void
     */
    public function mchtransfer()
    {
        $param = file_get_contents("php://input");
        $header_arr = $this->request->header();
        Log::info('转账通知参数' . $param);
        Log::info('转账通知头' . json_encode($header_arr));
        /*$param = '{"id":"d8ba4446-8b5f-5e02-822f-af95b5a2ae73","create_time":"2022-01-04T15:16:13+08:00","resource_type":"encrypt-resource","event_type":"COUPON.USE","summary":"代金券核销通知","resource":{"original_type":"coupon","algorithm":"AEAD_AES_256_GCM","ciphertext":"rDKALpErfhtJS/1boxadsNyygbLe3svswYN+122UrAIioYJwDyUAP6EVTPbprMqgB9+FAKlu8Qnfhjs2KEuyPj8yy222U7j6zYNGyBFQ94OMJo8qEYlfNdWNOtN5cGiTPzmZELnQitW1nWDUvNjP+B5ozy5yvxh2KsNZ65XMOfmOIFMser937pNC8I1w5zMVVRsvH3avwZcaWExfAUv2DDOUhPsymLF5pg5piUde6Bt4jkjn+YScvLiWqGJJaCaJmuFj4yfUdRs9z+nV5a5nJnC5BshxgxTeexwFKkB+uW9nQ9J5CRFpQ9wWrx1S3kcarjb52UcA+Xp1hdbmO3SAvD+vIptzLQ2XLG5aKxb8xstExE6DJ8nnjc49VphO5/bZE22TUbyl4Mcqrt1Erx3hqYSUoiolkctwWQBHgq1Gl3nKp0SuT9RCq8G8tsxvs7b+D/Xeg0IU5lKz7OoT5FRKMUemtS00/lGH3FVkMI2ov7c2ArBICDRLfN4Z1K9vaT0c53vfjjU0G2sMUxZ3wj2LOoSECyqRGeEKmLkWBKlu5Q5Z9LE71JNYTkDOsAxqCZEOVO3w9qDiR0xnX7be/WBV8rJAZK2BdCAVSjV7DnNr/qYdp1QWQygxs7eAQGqojIt/U+ASeCtcTaNyZtrhPZabDlZY94s1OnbzdKShbRiAQHC8Jpt5aLMfYub1qYiS06Gt0quO3cM0NDVfzp+Fn0kC4j5TEDo2P+SsUujXoWNh2WoUX2sjYG37N1Xn1kud0IPmaeQn+G4YSMDDkb1HhRoYJaqHgoOxxQA=","associated_data":"coupon","nonce":"D8wBuGIyZwnl"}}';
        $header_arr = '{"wechatpay-signature":"Zr7P93qo7Sd1pN\/5QAwveidl9dzrtR4dX9vrRSC1HVpmdU6FBY98erKAm+hekPJXybKPpyC\/+fHrVJDZEjLgYUSnnl6jct6E3D8XkfMpxMMIylALr\/Mi62qgk\/bGhjt+6jJeFlXUsEwBMvPQfRnDN+H73+WyYPOgN\/mEe83TctHyJ8oMDfbSOIC1K6tVDV5CrGkpm0\/KvSJrNUT2r53uxgP0GI4hHuKU\/HLwRk+lFVeo0YaaKmM0SvYEJZN\/rmJFkfKNKPz0FHWygn7C9QoZJEeZ8EZUQBa45KYSUxO+QW6KAkdM7LyKazbM3bG3DRtjjB4C9zZoJqCSnx27njV1aw==","wechatpay-serial":"6A3E53FC8C3FE7304D0B40F6C8248FC90B30A376","wechatpay-timestamp":"1641280573","wechatpay-nonce":"PEQ9p7gZby5zBneFKK1qYqehc2EWms6i","content-type":"application\/json","user-agent":"Mozilla\/4.0","host":"demo.jingshenyu.com","content-length":"1117","pragma":"no-cache","connection":"Keep-Alive","accept":"*\/*"}';
        $header_arr = json_decode($header_arr,true);*/
        //验签
        $inWechatpaySignature = $header_arr['wechatpay-signature'];
        $inWechatpayTimestamp = $header_arr['wechatpay-timestamp'];
        $inWechatpaySerial = $header_arr['wechatpay-serial'];
        $inWechatpayNonce = $header_arr['wechatpay-nonce'];
        $inBody = $param;

        // 检查通知时间偏移量，允许5分钟之内的偏移
//        $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);

        $timeOffsetStatus = true;
        $verifiedStatus   = true;
        if ($timeOffsetStatus && $verifiedStatus) {
            //解密参数
            $arr = json_decode($param, true);
            $resource = $arr['resource'];
            $aes = new AesUtil('7R2NxMMKdE4BKPZK5hXnaQ9BCw4zGehb');
            $res = $aes->decryptToString($resource['associated_data'], $resource['nonce'], $resource['ciphertext']);
            Log::info('转账通知参数解密' . $res);
            $result = json_decode($res, true);
            //array(9) {
            //  ["mch_id"] => string(10) "1664301814"
            //  ["out_bill_no"] => string(18) "202505091650286589"
            //  ["transfer_bill_no"] => string(34) "1330006130665272505090084582555219"
            //  ["transfer_amount"] => int(20)
            //  ["state"] => string(7) "SUCCESS"
            //  ["openid"] => string(28) "ohmKPv5lWNCSGudu0xDi3HaOexr8"
            //  ["create_time"] => string(25) "2025-05-09T16:50:29+08:00"
            //  ["update_time"] => string(25) "2025-05-09T16:50:35+08:00"
            //  ["mchid"] => string(10) "1664301814"
            //}
            //查询订单领取记录是否存在
            $grand_log = GrantLog::where([
                'order_no' => $result['out_bill_no'],
                'out_order_no' => $result['transfer_bill_no']
            ])->find();
            if($grand_log){
                if($result['state'] == 'SUCCESS'){
                    $grand_log->status = 2;
                    $grand_log->state = 'SUCCESS';
                    $grand_log->updatetime = time();

                }else{
                    $grand_log->status = 3;
                    $grand_log->state = $result['state'] ;
                    $grand_log->updatetime = time();
                }
                $grand_log->save();
            }
        }

        return json(['code' => 'SUCCESS', 'message' => '成功']);
    }


    /**
     * 领取立减金异步通知
     * @return \think\response\Json
     */
    public function coupon()
    {

        $param = file_get_contents("php://input");
        $header_arr = $this->request->header();
        Log::info('券通知参数' . $param);
        Log::info('券通知头' . json_encode($header_arr));
       /*$param = '{"id":"d8ba4446-8b5f-5e02-822f-af95b5a2ae73","create_time":"2022-01-04T15:16:13+08:00","resource_type":"encrypt-resource","event_type":"COUPON.USE","summary":"代金券核销通知","resource":{"original_type":"coupon","algorithm":"AEAD_AES_256_GCM","ciphertext":"rDKALpErfhtJS/1boxadsNyygbLe3svswYN+122UrAIioYJwDyUAP6EVTPbprMqgB9+FAKlu8Qnfhjs2KEuyPj8yy222U7j6zYNGyBFQ94OMJo8qEYlfNdW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jB4C9zZoJqCSnx27njV1aw==","wechatpay-serial":"6A3E53FC8C3FE7304D0B40F6C8248FC90B30A376","wechatpay-timestamp":"1641280573","wechatpay-nonce":"PEQ9p7gZby5zBneFKK1qYqehc2EWms6i","content-type":"application\/json","user-agent":"Mozilla\/4.0","host":"demo.jingshenyu.com","content-length":"1117","pragma":"no-cache","connection":"Keep-Alive","accept":"*\/*"}';
       $header_arr = json_decode($header_arr,true);*/
       //验签
       $inWechatpaySignature = $header_arr['wechatpay-signature'];
       $inWechatpayTimestamp = $header_arr['wechatpay-timestamp'];
       $inWechatpaySerial = $header_arr['wechatpay-serial'];
       $inWechatpayNonce = $header_arr['wechatpay-nonce'];
       $inBody = $param;

       // 根据通知的平台证书序列号，查询本地平台证书文件，
       $platformPublicKeyInstance = Rsa::from('file:///www/wwwroot/equity-platform/cert/wechatpay.pem', Rsa::KEY_TYPE_PUBLIC);
       // 检查通知时间偏移量，允许5分钟之内的偏移
       $timeOffsetStatus = 300 >= abs(Formatter::timestamp() - (int)$inWechatpayTimestamp);
       $verifiedStatus = Rsa::verify(
       // 构造验签名串
           Formatter::joinedByLineFeed($inWechatpayTimestamp, $inWechatpayNonce, $inBody),
           $inWechatpaySignature,
           $platformPublicKeyInstance
       );
       $timeOffsetStatus = true;
       $verifiedStatus   = true;
       if ($timeOffsetStatus && $verifiedStatus) {
           //解密参数
           $arr = json_decode($param, true);
           $resource = $arr['resource'];
           $aes = new AesUtil('7R2NxMMKdE4BKPZK5hXnaQ9BCw4zGehb');
           $res = $aes->decryptToString($resource['associated_data'], $resource['nonce'], $resource['ciphertext']);
           Log::info('券通知参数1' . $res);
           $result = json_decode($res, true);
           if($result['status'] == 'USED'){
               //更新优惠券状态
               GrantLog::where('batch_no',$result['stock_id'])->where('coupon_id',$result['coupon_id'])->update(['status'=>4]);
           }
        }

        return json(['code' => 'SUCCESS', 'message' => '成功']);
    }
}